package blogs.eidos.cloud.framework.core.interceptor;

import lombok.extern.slf4j.Slf4j;
import net.bigdata.cloud.framework.common.api.HttpCodeEnum;
import net.bigdata.cloud.framework.common.api.Resp;
import net.bigdata.cloud.framework.common.exception.UnAuthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;

/**
 * @author ： Eidos
 * @date ：Created in 2021/4/12
 * @description：
 * @modified By：
 * @version: 1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private Resp<?> commonExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return Resp.failed(HttpCodeEnum.INVOKE_FAILURE_ERROR);
    }

    @ExceptionHandler(value = ServerException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private Resp<?> serverExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return Resp.failed(HttpCodeEnum.INVOKE_FAILURE_ERROR);
    }


    @ExceptionHandler(value = UnAuthorizedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    private Resp<?> unAuthorizedExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return Resp.failed(HttpCodeEnum.ACCESS_DENIED_ERROR);
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    private Resp<?> methodArgumentNotValidExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.toString(), e);
        return Resp.failed(HttpCodeEnum.VALIDATE_ERROR);
    }

}
